package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.mapper.UserBasicMapper;
import org.example.model.common.dtos.PageResponseDto;
import org.example.model.common.dtos.user.LoginDto;
import org.example.model.common.dtos.user.UserBasicDto;
import org.example.model.common.vos.user.LoginVo;
import org.example.model.user.UserBasic;
import org.example.model.user.UserInfo;
import org.example.service.UserBasicService;
import org.example.service.UserInfoService;
import org.example.utils.JwtUtils;
import org.example.utils.MD5Utils;
import org.example.utils.PageUtils;
import org.example.utils.UserIdThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理
 */
@Service
@Slf4j
@Transactional
public class UserBasicServiceImpl extends ServiceImpl<UserBasicMapper, UserBasic> implements UserBasicService {

    @Autowired
    private UserBasicMapper userBasicMapper;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户登录
     *
     * @param loginVo 登录参数
     * @param flag false,移动端登录;true,PC端登录
     */
    @Override
    public LoginDto Login(LoginVo loginVo, Boolean flag) {
        LoginDto loginDto = new LoginDto();
        loginDto.setIsSuccess(false);
        if (loginVo == null) {
            return loginDto;
        }
        if (StringUtils.isBlank(loginVo.getLoginAccount()) || StringUtils.isBlank(loginVo.getPassword())) {
            loginDto.setMessage("登录账号或密码不能为空");
            return loginDto;
        }
        LambdaQueryWrapper<UserBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBasic::isIsDeleted,false);
        queryWrapper.eq(UserBasic::getLoginAccount,loginVo.getLoginAccount());
        List<UserBasic> userBasics = userBasicMapper.selectList(queryWrapper);
        if (userBasics == null || userBasics.size() <= 0) {
            loginDto.setMessage("该用户不存在");
            return loginDto;
        }
        for (UserBasic userBasic : userBasics) {
            if (userBasic.getStatus() == 2) {
                loginDto.setMessage("用户已禁用");
                return loginDto;
            }
            if (userBasic.getType() == 1 && flag) {
                loginDto.setMessage("该用户无权限登录后台管理系统");
                return loginDto;
            }
            if (userBasic.getPassword().equals(MD5Utils.encode(loginVo.getPassword()))) {
                loginDto.setAccessToken(JwtUtils.GenerateToken(userBasic));
                loginDto.setIsSuccess(true);
                loginDto.setUserId(userBasic.getId());
                loginDto.setMessage("登录成功");
                return loginDto;
            }
        }
        loginDto.setMessage("密码错误");
        return loginDto;
    }

    /**
     * 用户注册
     *
     * @param loginVo 注册参数
     */
    @Override
    public LoginDto Register(LoginVo loginVo) {
        LoginDto loginDto = new LoginDto();
        loginDto.setIsSuccess(false);
        if (loginVo == null) {
            return loginDto;
        }
        if (StringUtils.isBlank(loginVo.getLoginAccount()) || StringUtils.isBlank(loginVo.getPassword())) {
            loginDto.setMessage("登录账号或密码不能为空");
            return loginDto;
        }
        LambdaQueryWrapper<UserBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBasic::isIsDeleted,false);
        queryWrapper.eq(UserBasic::getLoginAccount,loginVo.getLoginAccount());
        List<UserBasic> userBasics = userBasicMapper.selectList(queryWrapper);
        Boolean flag = false;
        for (UserBasic userBasic : userBasics) {
            if (userBasic.getPassword().equals(MD5Utils.encode(loginVo.getPassword()))) flag = true;
        }
        if (!flag) {
            //该用户不存在，创建新用户
            UserBasic user = new UserBasic();
            user.setUsername(loginVo.getLoginAccount());
            user.setLoginAccount(loginVo.getLoginAccount());
            user.setPassword(MD5Utils.encode(loginVo.getPassword()));
            user.setStatus(1);
            user.setType(1);
            user.setIsDeleted(false);
            user.setCreateDate(LocalDateTime.now());
            user.setUpdateDate(LocalDateTime.now());
            userBasicMapper.insert(user);
            int userId = user.getId();
            UserBasic userBasic = userBasicMapper.selectById(userId);
            //生成一个默认的用户个人信息对象
            this.AddDefaultUserInfo(userBasic);
            userBasic.setCreateUser(userId);
            userBasic.setUpdateUser(userId);
            userBasic.setUpdateDate(LocalDateTime.now());
            loginDto.setIsSuccess(userBasicMapper.updateById(userBasic) > 0);
            loginDto.setMessage("注册成功");
            return loginDto;
        }
        loginDto.setMessage("该用户已存在");
        return loginDto;
    }

    //生成一个默认的用户个人信息对象
    private Boolean AddDefaultUserInfo(UserBasic userBasic)
    {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userBasic.getId());
        userInfo.setName(userBasic.getLoginAccount());
        userInfo.setSex("保密");
        userInfo.setDescription("一句话介绍自己");
        return userInfoService.InsertUserInfo(userInfo);
    }

    /**
     * 新增用户
     *
     * @param userBasic
     */
    @Override
    public Boolean InsertUserBasic(UserBasic userBasic) {
        //判断用户数据是否为空
        if (userBasic == null) return false;
        //判断用户密码是否为空
        if (StringUtils.isBlank(userBasic.getPassword())) return false;
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        //插入初始化数据
        userBasic.setPassword(MD5Utils.encode(userBasic.getPassword()));
        userBasic.setCreateUser(userId);
        userBasic.setCreateDate(LocalDateTime.now());
        userBasic.setUpdateUser(userId);
        userBasic.setUpdateDate(LocalDateTime.now());
        userBasic.setIsDeleted(false);
        //生成一个默认的用户个人信息对象
        userBasicMapper.insert(userBasic);
        Boolean flag = this.AddDefaultUserInfo(userBasic);
        if (!flag) return false;
        return true;
    }

    /**
     * 根据Id查询数据详情
     *
     * @param id
     * @return
     */
    @Override
    public UserBasicDto SelectUserById(int id) {
        if (id <= 0) return new UserBasicDto();
        UserBasic userBasic = userBasicMapper.selectById(id);
        if (userBasic == null) return new UserBasicDto();
        if (userBasic.isIsDeleted()) return new UserBasicDto();
        UserBasicDto userBasicDto = new UserBasicDto();
        //对象数据拷贝
        BeanUtils.copyProperties(userBasic,userBasicDto);
        //将创建人和修改人从Id->name
        int CreateId = userBasic.getCreateUser();
        int UpdateId = userBasic.getUpdateUser();
        if(CreateId <= 0 && UpdateId <= 0) return userBasicDto;
        if(CreateId > 0 && UpdateId > 0) {
            userBasicDto.setCreateUser(userBasicMapper.selectById(CreateId).getUsername());
            userBasicDto.setUpdateUser(userBasicMapper.selectById(UpdateId).getUsername());
            return userBasicDto;
        }
        if (CreateId > 0) {
            userBasicDto.setCreateUser(userBasicMapper.selectById(CreateId).getUsername());
        }
        if(UpdateId > 0) {
            userBasicDto.setUpdateUser(userBasicMapper.selectById(UpdateId).getUsername());
        }
        return userBasicDto;
    }

    /**
     * 根据id修改用户信息(包含修改密码操作)
     *
     * @param userBasic
     */
    @Override
    public Boolean UpdateUserBasicById(UserBasic userBasic) {
        if (userBasic == null) { return false; }
        //获取Token中的数据
        Integer userId = UserIdThreadLocalUtils.getUser();
        if (userId <= 0) return false;
        //数据库中的用户信息
        UserBasic user = userBasicMapper.selectById(userBasic.getId());
        user.setUpdateUser(userId);
        user.setUpdateDate(LocalDateTime.now());
        //判断密码是否为空
        if(!StringUtils.isBlank(userBasic.getPassword())) {
            //密码不为空，修改密码
            user.setPassword(MD5Utils.encode(userBasic.getPassword()));
        }else {
            //密码为空，不修改密码
            user.setUsername(userBasic.getUsername());
            user.setLoginAccount(userBasic.getLoginAccount());
            user.setIsDeleted(userBasic.isIsDeleted());
            user.setType(userBasic.getType());
            user.setStatus(userBasic.getStatus());
        }
        return userBasicMapper.updateById(user) > 0;
    }

    /**
     * 按条件(用户名模糊查询，登录账号模糊查询，用户状态精确查询,用户类型精确查询)分页查询
     *
     * @param userBasic
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public PageResponseDto<List<UserBasicDto>> SelectPageByConditions(UserBasic userBasic, int pageIndex, int pageSize) {
        LambdaQueryWrapper<UserBasic> queryWrapper = new LambdaQueryWrapper<>();
        // 用户名模糊查询，登录账号模糊查询，用户状态精确查询,用户类型精确查询
        queryWrapper
                .eq(UserBasic::isIsDeleted,false)
                .like(StringUtils.isNotBlank(userBasic.getUsername()),UserBasic::getUsername,userBasic.getUsername())
                .like(StringUtils.isNotBlank(userBasic.getLoginAccount()),UserBasic::getLoginAccount,userBasic.getLoginAccount())
                .eq(userBasic.getType() != 0,UserBasic::getType,userBasic.getType())
                .eq(userBasic.getStatus() != 0,UserBasic::getStatus,userBasic.getStatus())
                .orderByDesc(UserBasic::getCreateDate);

        List<UserBasic> userBasics = userBasicMapper.selectList(queryWrapper);
        List<UserBasicDto> userBasicDtoList = new ArrayList<>();
        if (userBasics.size() == 0) return new PageResponseDto<>();
        UserBasicDto userBasicDto = null;
        for (int i = 0; i < userBasics.size(); i++) {
            userBasicDto = new UserBasicDto();
            BeanUtils.copyProperties(userBasics.get(i),userBasicDto);
            userBasicDtoList.add(userBasicDto);
        }
        userBasicDtoList = userBasicDtoList.stream().map((item) -> {
            item = this.SelectUserById(item.getId());
            return item;
        }).collect(Collectors.toList());
        PageResponseDto<List<UserBasicDto>> pageResponseDto = new PageResponseDto<>();
        pageResponseDto.setSize(userBasicDtoList.size());
        //分页
        pageResponseDto.setData(new PageUtils<UserBasicDto>().page(userBasicDtoList,pageIndex,pageSize));
        return pageResponseDto;
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    @Override
    public Boolean DeleteUserBasicById(int id) {
        if (id <= 0) return false;
        UserBasic userBasic = userBasicMapper.selectById(id);
        userBasic.setPassword(null);
        userBasic.setIsDeleted(true);
        return this.UpdateUserBasicById(userBasic);
    }
}
